import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useTabsStore = defineStore('tabs', () => {
  // 页签列表
  const tabsList = ref([
    {
      path: '/dashboard',
      name: 'Dashboard',
      title: '仪表板',
      closable: false, // 首页不可关闭
    },
  ]);

  // 当前激活的页签
  const activeTab = ref('/dashboard');

  /**
   * 添加页签
   * @param {Object} route - 路由对象
   * @param {Object} router - 路由实例（可选，用于查找完整路由配置）
   */
  const addTab = (route, router = null) => {
    // 跳过不需要显示页签的页面
    if (route.meta?.hidden || route.path === '/') {
      return;
    }

    // 从路由表中查找完整的路由配置（用于判断是否是父路由）
    let fullRouteConfig = null;
    if (router) {
      const allRoutes = router.getRoutes();
      fullRouteConfig = allRoutes.find(r => r.path === route.path);
    }

    // 跳过有重定向的父路由（这些路由不应该显示tab）
    // 检查传入的 route 对象或从路由表查找到的完整配置
    const hasRedirect = route.redirect || fullRouteConfig?.redirect;
    const hasChildren = (route.children && route.children.length > 0) || 
                       (fullRouteConfig?.children && fullRouteConfig.children.length > 0);
    
    if (hasRedirect && hasChildren) {
      return;
    }

    // 检查页签是否已存在
    const index = tabsList.value.findIndex((tab) => tab.path === route.path);
    
    if (index === -1) {
      // 添加新页签
      tabsList.value.push({
        path: route.path,
        name: route.name,
        title: route.meta?.title || route.name,
        closable: route.path !== '/dashboard', // 仪表板不可关闭
      });
    }

    // 设置当前激活页签
    activeTab.value = route.path;
  };

  /**
   * 删除页签
   * @param {String} path - 页签路径
   */
  const removeTab = (path) => {
    const index = tabsList.value.findIndex((tab) => tab.path === path);
    
    if (index === -1) return;

    // 不能删除不可关闭的页签
    if (!tabsList.value[index].closable) return;

    // 如果删除的是当前激活的页签，需要切换到其他页签
    if (activeTab.value === path) {
      // 优先切换到右侧页签，如果没有则切换到左侧
      const nextTab = tabsList.value[index + 1] || tabsList.value[index - 1];
      if (nextTab) {
        activeTab.value = nextTab.path;
      }
    }

    // 删除页签
    tabsList.value.splice(index, 1);

    return activeTab.value;
  };

  /**
   * 关闭其他页签
   * @param {String} path - 保留的页签路径
   */
  const closeOtherTabs = (path) => {
    tabsList.value = tabsList.value.filter(
      (tab) => tab.path === path || !tab.closable
    );
    activeTab.value = path;
  };

  /**
   * 关闭右侧页签
   * @param {String} path - 当前页签路径
   */
  const closeRightTabs = (path) => {
    const index = tabsList.value.findIndex((tab) => tab.path === path);
    if (index === -1) return;

    tabsList.value = tabsList.value.filter((tab, i) => {
      return i <= index || !tab.closable;
    });
  };

  /**
   * 关闭所有页签
   */
  const closeAllTabs = () => {
    tabsList.value = tabsList.value.filter((tab) => !tab.closable);
    activeTab.value = '/dashboard';
  };

  /**
   * 刷新页签（用于页面刷新后恢复页签）
   */
  const refreshTabs = () => {
    // 这里可以从 localStorage 恢复页签
    // 或者保持默认的首页页签
  };

  return {
    tabsList,
    activeTab,
    addTab,
    removeTab,
    closeOtherTabs,
    closeRightTabs,
    closeAllTabs,
    refreshTabs,
  };
});
